package com.xs.ahoi.hcxs.utils;

import android.graphics.*;

/**
 * author: ahoi
 * date: 2018/7/12 18:27
 * description:
 */
public class ShortCutUtil {

    // 原图尺寸
    private int width;
    private int height;
    // 画布
    private Canvas canvas;
    // 画布底图
    private Bitmap backBitmap;
    // 画笔
    private Paint mPaint;
    // 矩形
    private Rect rect;
    // 圆角矩形
    private RectF rectF;
    // 阴影过滤器
    private BlurMaskFilter maskfilter;

    public ShortCutUtil() {
        this.width = Constants.SHORT_CUT_WIDTH;
        this.height = Constants.SHORT_CUT_HEIGHT;
        init();
    }

    // 初始化
    private void init() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.BLACK);

        rect = new Rect(0, 0, width, height);
        rectF = new RectF(rect);

        maskfilter = new BlurMaskFilter(20, BlurMaskFilter.Blur.NORMAL);
    }

    // 生成圆角 + 阴影
    public Bitmap getRoundAndShadow(Bitmap source, float radius) {

        // 圆角图片
        Bitmap sourceBitmap = createRound(source, radius);

        // 创建画布
        backBitmap = Bitmap.createBitmap(width + 40, height + 40, Bitmap.Config.ARGB_8888);
        canvas = new Canvas(backBitmap);

        // 创建阴影画笔
        mPaint.setColor(Color.BLACK);
        mPaint.setMaskFilter(maskfilter);

        // 绘制阴影
        Bitmap shadowBitmap = sourceBitmap.extractAlpha();
        int left = (backBitmap.getWidth() - shadowBitmap.getWidth()) / 2;
        int top = (backBitmap.getHeight() - shadowBitmap.getHeight()) / 2;
        canvas.drawBitmap(shadowBitmap, left, top, mPaint);
        mPaint.setMaskFilter(null);
        canvas.drawBitmap(sourceBitmap, left, top, mPaint);

        // 绘制圆角边框
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(Color.BLACK);
        mPaint.setStrokeWidth(3f);
        canvas.drawRoundRect(left, top, left + width, top + height, radius, radius, mPaint);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setStrokeWidth(0);

        return backBitmap;
    }

    // 生成圆角
    private Bitmap createRound(Bitmap source, float radius) {
        backBitmap = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
        canvas = new Canvas(backBitmap);

        // 绘制目标图
        canvas.drawRoundRect(rectF, radius, radius, mPaint);
        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

        // 绘制源图
        canvas.drawBitmap(source, rect, rect, mPaint);
        mPaint.setXfermode(null);
        return backBitmap;
    }

}
